﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace CustomWindows.Window_API
{
    public class WindowMover: WindowsFunction
    {
		#region Fields (1) 

        private readonly Keys _leftOrRight;

		#endregion Fields 

		#region Constructors (1) 

        public WindowMover(IntPtr hwnd, Keys leftOrRight) : base(hwnd)
        {
            _leftOrRight = leftOrRight;
            Description = "WindowMover";
            EventLogger = new Event(DateTime.Now, Hwnd, Description);
        }

		#endregion Constructors 

		#region Methods (1) 

		// Public Methods (1) 

        public override void UpdateFunction()
        {
            var screen = Screen.PrimaryScreen;
            var activeWindow = new Rectangle();
            GetWindowRect(Hwnd, ref activeWindow);

            var locationOnScreen = activeWindow.X;

            switch (_leftOrRight)
            {
                case Keys.Left:
                    if (activeWindow.X >= (screen.Bounds.Width / 2))
                    {//User wants to move window from right to LEFT
                        locationOnScreen -= (screen.Bounds.Width / 2);
                    }
                    break;
                case Keys.Right:
                    if (activeWindow.X < (screen.Bounds.Width / 2))
                    {//User wants to move window from left to right
                        locationOnScreen += (screen.Bounds.Width / 2);
                    }
                    break;
            }
            MoveWindow(Hwnd, locationOnScreen, activeWindow.Y, activeWindow.Width - activeWindow.X, activeWindow.Height - activeWindow.Y, true);
        }

		#endregion Methods 

        #region API

        [DllImport("user32.dll")]
        public static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool bRepaint);
        [DllImport("user32.dll")]
        public static extern long GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);

        #endregion
    }
}
